package apis

import (
	"ssdevice/common/dto"
	"ssdevice/internal/device/models/command"

	"gitee.com/sansaniot/ssiot-core/httpmvc/api"
	"gitee.com/sansaniot/ssiot-core/serrors"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"

	"ssdevice/internal/device/models"
	"ssdevice/internal/device/models/query"
	"ssdevice/internal/device/service"
)

type Tag struct {
	api.Api
}

// FindPage 分页查询标签
func (e Tag) FindPage(c *gin.Context) {
	req := query.SysTagQuery{}
	tagModel := &models.SysTag{}

	err := e.MakeContext(c).
		Bind(&req, binding.Form).
		MakeModel(&tagModel.Model).
		Errors

	if err != nil {
		e.Fail(0, err.Error())
		return
	}

	list, count, err := tagModel.FindPage(&req)
	if err != nil {
		e.Fail(0, err.Error())
		return
	}

	e.Page(count, req.GetPageSize(), req.GetPageIndex(), list)
}

// FindOne 获取单个标签
func (e Tag) FindOne(c *gin.Context) {
	req := query.SysTagQuery{}
	tagModel := &models.SysTag{}

	err := e.MakeContext(c).
		Bind(&req, binding.Form).
		MakeModel(&tagModel.Model).
		Errors

	if err != nil {
		e.Fail(0, err.Error())
		return
	}

	err = tagModel.FindOne(tagModel, dto.MakeCondition(req.GetNeedSearch()))
	if err != nil {
		e.Fail(0, err.Error())
		return
	}

	e.Data(tagModel)
}

// AddTag 新增标签
func (e Tag) AddTag(c *gin.Context) {
	req := command.TagInsertReq{}
	tag := &models.SysTag{}

	err := e.MakeContext(c).
		MakeModel(&tag.Model).
		Bind(&req, binding.JSON).
		Errors

	if err != nil {
		e.Fail(serrors.InvalidParam)
		return
	}

	err = req.Generate(tag)
	if err != nil {
		e.Fail(serrors.InvalidParam)
		return
	}

	// 使用新的CreateOrGetByName方法，如果标签名已存在则返回已存在标签的ID
	tagId, err := tag.CreateOrGetByName()
	if err != nil {
		e.Fail(serrors.InsertFail)
		return
	}

	e.Ok(tagId)
}

// RemoveTag 删除标签
func (e Tag) RemoveTag(c *gin.Context) {
	req := command.TagReq{}
	s := &service.Tag{}
	tag := &models.SysTag{}

	err := e.MakeContext(c).
		MakeModel(&tag.Model).
		Bind(&req, binding.JSON).
		Errors

	if err != nil {
		e.Fail(serrors.InvalidParam)
		return
	}

	_ = req.Generate(tag)
	s.SetModel(tag)

	err = s.BatchDelete(req.Ids)
	if err != nil {
		e.Fail(serrors.DeleteFail)
		return
	}

	e.Ok(tag.Id)
}

func (e Tag) GetTagDeviceStats(c *gin.Context) {
	req := query.DeviceTagStatsReq{}
	tag := &models.SysTag{}
	userExt := &models.SysUserExt{}

	err := e.MakeContext(c).
		MakeModel(&tag.Model, &userExt.Model).
		Bind(&req, binding.Query).
		Errors

	if err != nil {
		e.Fail(serrors.InvalidParam)
		return
	}

	req.LoadUser(c)
	req.GetNeedSearch()
	total, err := userExt.GetTagTotal(req.UserName, req.TagName)

	stats, err := tag.GetTagDeviceStats(req.TagName, total, req.UserName, req.DeptIdIn)
	if err != nil {
		e.Fail(0, err.Error())
		return
	}

	e.Data(stats)
}
